const Calculator = require('../../../utils/calculator');

Page({
  data: {
    display: '0',
    expression: '',
    history: [],
    showHistory: false,
    isScientific: false,
    memory: 0,
    lastResult: null
  },

  onLoad() {
    this.calculator = new Calculator();
    this.loadHistory();
  },

  // 数字输入
  inputNumber(e) {
    const num = e.currentTarget.dataset.num;
    const { display, expression } = this.data;
    
    if (display === '0' || display === 'Error' || this.data.lastResult !== null) {
      this.setData({
        display: num,
        expression: num,
        lastResult: null
      });
    } else {
      this.setData({
        display: display + num,
        expression: expression + num
      });
    }
  },

  // 运算符输入
  inputOperator(e) {
    const operator = e.currentTarget.dataset.operator;
    let { expression, display } = this.data;
    
    // 如果上次有计算结果，使用结果作为新表达式的开始
    if (this.data.lastResult !== null) {
      expression = this.data.lastResult.toString();
      this.setData({ lastResult: null });
    }
    
    // 避免连续运算符
    if (/[+\-*/]$/.test(expression)) {
      expression = expression.slice(0, -1);
    }
    
    const newExpression = expression + operator;
    this.setData({
      expression: newExpression,
      display: newExpression
    });
  },

  // 小数点
  inputDot() {
    const { display, expression } = this.data;
    
    // 检查当前数字是否已有小数点
    const parts = expression.split(/[+\-*/]/);
    const currentNumber = parts[parts.length - 1];
    
    if (!currentNumber.includes('.')) {
      this.setData({
        display: display + '.',
        expression: expression + '.'
      });
    }
  },

  // 计算结果
  calculate() {
    const result = this.calculator.calculate(this.data.expression);
    
    if (result !== 'Error') {
      this.setData({
        display: result.toString(),
        lastResult: result,
        expression: '',
        history: this.calculator.history
      });
      this.saveHistory();
    } else {
      this.setData({
        display: 'Error'
      });
      wx.showToast({
        title: '计算错误',
        icon: 'none'
      });
    }
  },

  // 清除
  clear() {
    this.setData({
      display: '0',
      expression: '',
      lastResult: null
    });
  },

  // 清除全部
  clearAll() {
    this.setData({
      display: '0',
      expression: '',
      lastResult: null,
      memory: 0
    });
  },

  // 删除最后一位
  backspace() {
    let { display, expression } = this.data;
    
    if (display.length > 1) {
      display = display.slice(0, -1);
      expression = expression.slice(0, -1);
    } else {
      display = '0';
      expression = '';
    }
    
    this.setData({ display, expression });
  },

  // 科学计算函数
  inputFunction(e) {
    const func = e.currentTarget.dataset.func;
    const { expression } = this.data;
    
    let newExpression = expression;
    
    switch (func) {
      case 'sin':
      case 'cos':
      case 'tan':
      case 'log':
      case 'ln':
      case 'sqrt':
        newExpression += func + '(';
        break;
      case 'pi':
        newExpression += 'π';
        break;
      case 'e':
        newExpression += 'e';
        break;
      case 'pow':
        newExpression += '^';
        break;
      case 'bracket':
        newExpression += '(';
        break;
      case 'bracket_close':
        newExpression += ')';
        break;
    }
    
    this.setData({
      expression: newExpression,
      display: newExpression
    });
  },

  // 内存操作
  memoryOperation(e) {
    const operation = e.currentTarget.dataset.operation;
    const currentValue = parseFloat(this.data.display) || 0;
    
    switch (operation) {
      case 'mc': // Memory Clear
        this.setData({ memory: 0 });
        break;
      case 'mr': // Memory Recall
        this.setData({
          display: this.data.memory.toString(),
          expression: this.data.memory.toString(),
          lastResult: this.data.memory
        });
        break;
      case 'ms': // Memory Store
        this.setData({ memory: currentValue });
        break;
      case 'mp': // Memory Plus
        this.setData({ memory: this.data.memory + currentValue });
        break;
      case 'mm': // Memory Minus
        this.setData({ memory: this.data.memory - currentValue });
        break;
    }
    
    wx.showToast({
      title: `内存: ${this.data.memory}`,
      icon: 'none',
      duration: 1000
    });
  },

  // 切换科学计算器模式
  toggleScientific() {
    this.setData({
      isScientific: !this.data.isScientific
    });
  },

  // 显示/隐藏历史记录
  toggleHistory() {
    this.setData({
      showHistory: !this.data.showHistory
    });
  },

  // 使用历史记录
  useHistory(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      display: item.result.toString(),
      expression: '',
      lastResult: item.result,
      showHistory: false
    });
  },

  // 清除历史记录
  clearHistory() {
    this.calculator.history = [];
    this.setData({ history: [] });
    this.saveHistory();
    wx.showToast({
      title: '历史记录已清除',
      icon: 'success'
    });
  },

  // 保存历史记录
  saveHistory() {
    wx.setStorageSync('calculator_history', this.calculator.history);
  },

  // 加载历史记录
  loadHistory() {
    const history = wx.getStorageSync('calculator_history') || [];
    this.calculator.history = history;
    this.setData({ history });
  },

  // 复制结果
  copyResult() {
    wx.setClipboardData({
      data: this.data.display,
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        });
      }
    });
  }
});